const mime = require("./mime");
const fs = require("fs");
module.exports = function (app) {
    app.getClientIP = (req) => req.headers['x-real - ip'] || req.headers['x - forwarded -for'] || req.connection.remoteAddress;
    app.errorLog = (r) => console.error({ "path": r.path, "ip": app.getClientIP(r.req), err: r.err, errCode: r.errCode });
    app.error = (r) => {
        app.errorLog(r);
        r.res.writeHead(r.errCode, { 'Content-Type': 'text/html' });
        r.res.write(r.errCode.toString());
        r.res.end();
    };
    app.static = [];
    app.serve = (r) => {
        let path = r.path.replace(/^\/+/, "");
        if (app.static.length == 0) return app.error404(r);
        let s = app.static.find(_ => path.indexOf(_) == 0);
        if (s) {
            let t = mime.getType(path);
            return fs.readFile(path, function (err, fr) {
                if (err) {
                    app.error404(r);
                } else {
                    r.res.writeHead(200, { 'Content-Type': t });
                    r.res.write(fr);
                    r.res.end();
                }
            });
        }
    };
    app.moveFile = (op, np) => fs.renameSync(op, np);
    app.copyFile = (op, np) => fs.writeFileSync(np, fs.readFileSync(op));
    app.readJSON = (p) => JSON.parse(fs.readFileSync(p));
    app.writeJSON = (p, d) => fs.writeFileSync(p, JSON.stringify(d));
    app.readText = (p) => fs.readFileSync(p, 'utf-8');
    return app;
};
